<template>
  <div class="app-container">

   <div class="filter-container">
    
      <el-select v-model="selectValue"  placeholder="请选择" class='inp_search'>
          <el-option
          v-for="item in optionsData"
          :key="item.value"
          :label="item.label"
          :value="item.value">
          </el-option>
      </el-select>
      
      <el-input
          placeholder="输入查询"
          v-model="input_conten"
          clearable class='inp_search'>
      </el-input>

      <el-button  class="filter-item" type="primary" icon="el-icon-search" @click="searchList">
        搜索
      </el-button>
      <el-button  v-if="role== '4'" class="filter-item" type="success" icon="el-icon-plus" @click="addStock('add')">
        添加
      </el-button>
      <el-button  class="filter-item" type="primary" icon="el-icon-refresh"  @click="resList">
        重置
      </el-button>
    </div>
     
     <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >

    <el-table-column label="优惠券ID" min-width="200" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.couponId === null">--</span>
          <span v-else> {{scope.row.couponId}} </span>
        </template>
    </el-table-column>

    <el-table-column label="用户手机号" width="120" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.userPhone === null">--</span>
          <span v-else> {{scope.row.userPhone}} </span>
        </template>
      </el-table-column>

      <el-table-column label="卡券金额" min-width="200" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.price === null">--</span>
          <span v-else> {{scope.row.price}} </span>
        </template>
      </el-table-column>

      <el-table-column label="状态" min-width="200" align="center">
        <template slot-scope="scope"> 
          <!-- 1：已使用 0：未使用 -->
          <span v-if='scope.row.state === 1'>已使用</span>
          <span v-else>未使用</span>
        </template>
      </el-table-column>

      <el-table-column label="订单ID" min-width="200" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.orderId === null">--</span>
          <span v-else> {{scope.row.orderId}} </span>
        </template>
      </el-table-column>

      <el-table-column label="优惠券名称" min-width="200" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.couponName === null">--</span>
          <span v-else> {{scope.row.couponName}} </span>
        </template>
      </el-table-column>

      <el-table-column label="开始时间" min-width="200" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.beginDate === null">--</span>
          <span v-else> {{handel(scope.row.beginDate)}} </span>
        </template>
      </el-table-column>

      <el-table-column label="到期时间" min-width="200" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.endDate === null">--</span>
          <span v-else> {{handel(scope.row.endDate)}} </span>
        </template>
      </el-table-column>

      <el-table-column  v-if="role== '4'" label="操作" width="120" align="center" fixed="right">
        <template scope="scope">
					<el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
				</template>
      </el-table-column>
    </el-table>
   <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"  @pagination="fetchData"/>

   <!-- 添加 -->
   <div class='formPosition' v-if='dialogFormVisible'>
   <div class='titleForm'>
          <div class='left_titleForm'>{{titleName}}</div>
          <span class="icon iconfont right_titleForm" @click="dialogFormVisible = false">&#xe72d;</span>
   </div>
   <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm " :visible.sync="dialogFormVisible">
         
          <el-form-item  label="用户手机号" prop='userPhone'>
          <el-input v-model="ruleForm.userPhone"></el-input>
          </el-form-item>

          <el-form-item  label="卡券金额" prop='price'>
          <el-input v-model.number="ruleForm.price"></el-input>
          </el-form-item>

          <el-form-item v-if="this.titleName == '修改'" label="状态" prop='state' >
          <el-input v-model="ruleForm.state" ></el-input>
          </el-form-item>

          <el-form-item v-if="this.titleName == '修改'"  label="订单ID" prop='orderId' >
          <el-input v-model="ruleForm.orderId" ></el-input>
          </el-form-item>

          <el-form-item v-if="this.titleName == '修改'" label="优惠券ID" prop='couponId' >
          <el-input v-model="ruleForm.couponId" ></el-input>
          </el-form-item>

          <el-form-item  label="优惠券名称" prop='couponName'>
          <el-input v-model="ruleForm.couponName"></el-input>
          </el-form-item>

          <el-form-item  label="有效期" >
              <el-date-picker
                v-model="timeValue"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions2">
              </el-date-picker>
          </el-form-item> 
          
          <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
          </el-form-item>
     </el-form>
    </div>
  </div>
   
   
  
</template>

<script>
import { getCardTicketList ,addCardTicket ,modifyCardTicke ,searchByphone } from '@/api/cardTicketManages'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
export default {
  components: { Pagination },
  data() {
    return {
       pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
       },
       role:'',
      timeValue: '', //["2020-01-12T16:00:00.000Z","2020-01-30T16:00:00.000Z"]
      input_conten:'',
      optionsData: [{
          value: 'userPhone',
          label: '用户手机号'
        }],
      selectValue: '',
      titleName:'',
      list: null,
      listLoading: true,
      total: 0,
      dialogFormVisible:false,
      NEWDATASTAR:'',
      NEWDATAEND:'',
      listQuery:{
           page: 1,
           limit: 10,
      },
      ruleForm: {
          beginDate:'',
          endDate:'',
          couponId:'',
          couponName:'',
          price: '',
          state:'',
          userPhone:'',
          orderId:''
        },
      cleanForm:{
          beginDate:'',
          endDate:'',
          couponId:'',
          couponName:'',
          price: '',
          state:'',
          userPhone:'',
          orderId:''
      },
        rules: {
          couponName: [
            { required: true, message: '请输入优惠券名称', trigger: 'blur' }
          ],
          price: [
            {type: 'number',required: true, message: '请输入正确格式的金额', trigger: 'blur'}
          ],
          userPhone: [
            {required: true, message: '请输入用户手机号', trigger: 'blur' },
            {
            pattern: /^1[0-9]{10}$/,
            message: '用户手机号格式不对',
            trigger: 'blur'
          },
          ],
        }
    }
  },
  created() {
    const userInfo  = localStorage.getItem('userInfo');
    this.role = JSON.parse(userInfo).role;
    this.fetchData()
    this.selectValue = this.optionsData[0].label;
    this.selectValue = "userPhone";
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const paramsData = {curPage:this.listQuery.page,pageSize:this.listQuery.limit}
      getCardTicketList(paramsData).then(res => {
        this.total = res.data.countNum;
        this.list = res.data.obj;
        this.listLoading = false
      })
    },
    handel(date){
        const newDate = date.substring(0,10);
        return newDate;
    },
   submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
             this.listLoading = true
            if(this.titleName === "添加"){
               this.handleAdd(formName)
            }else{
               this.handleModify(formName)
            }
            this.listLoading = false;
            this.resetForm(formName) 
          } else {
            console.log('提交失败');
            return false;
          }
        });
      },
       handleAdd(formName){//添加
            if(this.timeValue){
                this.ruleForm.beginDate = this.transformDate(this.timeValue[0])
                this.ruleForm.endDate = this.transformDate(this.timeValue[1])
            }
            const paramsData = {
                couponName:this.ruleForm.couponName,
                userPhone:this.ruleForm.userPhone,
                price:this.ruleForm.price,
                beginDate:this.ruleForm.beginDate,
                endDate:this.ruleForm.endDate
                }
              addCardTicket(paramsData).then(res => {
                this.list = res.data;
               if(res.code == '200'){
                        this.$notify({
                        message: '添加成功',
                        type: 'success',
                        duration: 2000
                    })
                  }else{
                    this.$notify({
                        message: '添加失败',
                        type: 'error',
                        duration: 2000
                    })
                  }
                  this.fetchData()//获取列表
            })
      },
      handleModify(formName){//修改
          if(this.timeValue){
                this.ruleForm.beginDate = this.transformDate(this.timeValue[0])
                this.ruleForm.endDate = this.transformDate(this.timeValue[1])
            }
             const paramsData = {
                  couponId:this.ruleForm.couponId,
                  couponName:this.ruleForm.couponName,
                  userPhone:this.ruleForm.userPhone,
                  price:this.ruleForm.price,
                  state: this.ruleForm.state,
                  orderId:this.ruleForm.orderId,
                  beginDate:this.ruleForm.beginDate,
                  endDate:this.ruleForm.endDate
                  }
                modifyCardTicke(paramsData).then(res => {
                  this.list = res.data;
                  if(res.code == '200'){
                        this.$notify({
                        message: '修改成功',
                        type: 'success',
                        duration: 2000
                    })
                  }else{
                    this.$notify({
                        message: '修改失败',
                        type: 'error',
                        duration: 2000
                    })
                  }
                  this.fetchData()//获取列表
              })
      },
      resetForm(formName) {
          this.ruleForm = this.cleanForm;
          this.$refs.ruleForm.resetFields();
          this.dialogFormVisible = false; 
      },
      addStock(formName){//处理弹出框添加和修改的状态
          this.dialogFormVisible = true;     
          this.titleName = '添加'
      },
      transformDate(d){
       const newData = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();   
       return newData
      },
      handleEdit(index, row ) {//修改
          this.titleName = '修改'
          this.timeValue =  [new Date(row.beginDate.substring(0,4), row.beginDate.substring(5,6), row.beginDate.substring(8,10)), new Date(row.endDate.substring(0,4), row.endDate.substring(5,6), row.endDate.substring(8,10))]
          this.ruleForm.beginDate = row.beginDate;
          this.ruleForm.endDate = row.endDate;
          this.dialogFormVisible = true;
          this.ruleForm = Object.assign({}, row);
      },
      resList(){
          const userInfo  = localStorage.getItem('userInfo');
          this.role = JSON.parse(userInfo).role;
          this.fetchData()
          this.selectValue = this.optionsData[0].label;
          this.selectValue = "userPhone";
      },
      searchList(){//搜索
         if(this.input_conten){
              const paramsData = {userPhone:this.input_conten,curPage:this.listQuery.page,pageSize:this.listQuery.limit}
              searchByphone(paramsData).then(res => {
                    this.list = res.data.obj;
                })
            
         }else{
           this.fetchData();
          //  this.$notify({
          //           message: '请先输入搜索内容',
          //           type: 'error',
          //           duration: 2000
          //       })
            return false;
         }

      }
    }
  
 }
</script>
<style lang="scss">
 .filter-container{
   margin-bottom:20px;
 }
 .el-date-range-picker{
   margin-left:25%;
 }
 .inp_search{
   width:20%;
   margin-right:1%;        
 }
 .formPosition{
    width:70%;
    height:auto;
    background:#fff;
    position:absolute;
    left:15%;
    top:5%;
    z-index:999;
    padding:30px;
    box-shadow: 0px 0px 5px 5px #eee;
    border-radius: 5px;
 }
 .demo-ruleForm{
      width:50%;     
 }
 .titleForm{
     width:100%;
     height:30px;
     line-height:30px;
     margin-bottom:20px;
     font-size:1.1em;
     font-weight: 500;
 }
 .left_titleForm{
    float:left;
 }
 .right_titleForm{
    display:block;
    float:right;
 }
 .select_roles{
    width:100%;
 }
 
</style>
